package com.herohead.backup;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.PropertiesConfiguration;
import org.apache.log4j.Logger;








import redis.clients.jedis.Jedis;

import com.herohead.*;
import com.herohead.pushco.PushCo;
import com.herohead.redis.GetRedisServer;
import com.rabbitmq.client.AMQP;
import com.rabbitmq.client.Channel;

public class AV_MonthlyReports {
	public static PreparedStatement report = null;

	private static org.apache.log4j.Logger log= Logger.getLogger(AV_MonthlyReports.class);
	
	static Connection connection = null;

	public static String startDate = "2013-08-01";
	public static String endDate = "2013-08-30";
	public static long  badNum = 0;
	public static long goodNum = 0;
	public static long totalNum = 0;
	public static float perSucceeded = 0;
	public static int aveBackups = 0;
	public static String gc_details = "";

	/**
	 * @param args
	 * @throws Exception 
	 * @throws ConfigurationException 
	 */
	@SuppressWarnings("deprecation")
	public static void main(String[] args) throws Exception, ConfigurationException {
		// TODO Auto-generated method stub
		
		
		
		CDLogger l = new CDLogger();
		l.programStart(log);
		String className = "AV_MonthlyReports";
		PropertiesConfiguration config = new PropertiesConfiguration(className + ".config");
		config.setAutoSave(true);
		
		log.debug("Reading configuration file - " + className + ".config" );
		
		String rabbitServer = config.getString("rabbitmqserver");
		String RMQVirtualHost = config.getString("RMQVirtualHost");
		String RMQUsername = config.getString("RMQUsername");
		String RMQPassword = config.getString("RMQPassword");
		String RMQQueue = config.getString("RMQQueue");

		String toEmail = config.getString("toEmail");
		String fromEmail = config.getString("fromEmail");
		
		
		Class.forName("org.postgresql.Driver");
		connection = DriverManager.getConnection("jdbc:postgresql://us00s-avamar01.am.mt.mtnet:5555/mcdb","viewuser", "viewuser1");

		Misc m = new Misc();

		startDate = m.getCurrentYear() + "-" + m.getCurrentMonth() + "-" + "01";
		endDate = m.getCurrentYear() + "-" + m.getCurrentMonth() + "-" + m.getMaxDaysInMonth();
		
		
		
		
		
		
		String yr = null;
		String mn = null;
		String dy = null;
		
		
		if (args.length > 1) {
			startDate = args[0];
			endDate = args[1];
			yr = startDate.split("-")[0];
			mn = startDate.split("-")[1];
		} else {
			yr = m.getCurrentYear();
			mn = m.getCurrentMonth();
			dy = m.getMaxDaysInMonthStr();
			
			startDate = yr + "-" + mn + "-01";
			endDate = yr + "-" + mn + "-" + dy;
			
		}
		
		//startDate = "2014-06-16";
		//endDate =  "2014-06-27";
		
		
		String redisKeys = "avamar:report:" + yr + "." + mn;
		
		//startDate = args[0];
		//endDate = args[1];
		
		
		
		//System.out.println("Start Date: - " + startDate);
		//System.out.println("End Date: - " + endDate);
		//System.out.println(redisKeys);
		
		
		//System.exit(0);
		
		GetRedisServer gs = new GetRedisServer();
			
		Jedis jd = new Jedis(gs.getRedisHost());
		
		jd.select(1);
		
		//connection = DriverManager.getConnection("jdbc:postgresql://us30s-avamar01.am.mt.mtnet:5555/mcdb","viewuser", "viewuser1");
		//report  = connection.prepareStatement("select Client_name from v_activities_2 where Client_name = 'us40s-util01.am.mt.mtnet'");
		//System.out.println("Active Clients: " + backupClientCount(connection));		
		//ResultSet resultSet = report.executeQuery();
		//writeResultSet(resultSet);
		monthReport(connection);
		System.out.println("Good Backups : " + goodNum);
		System.out.println("Bad Backups : " + badNum);
		System.out.println("Total Backups : " + totalNum);
		System.out.println("Percent Succeeded : " + perSucceeded);
		System.out.println("Average backup per day : " + aveBackups);
		
		jd.hset(redisKeys, "Good.backups", String.valueOf(goodNum));
		jd.hset(redisKeys, "Bad.Backups", String.valueOf(badNum));
		jd.hset(redisKeys, "Total.Backups", String.valueOf(totalNum));
		jd.hset(redisKeys, "Percent.Succeeded", String.valueOf(perSucceeded));
		jd.hset(redisKeys, "Average.backup.per.day", String.valueOf(aveBackups));
		
		
		
		
		gc_details = GarbageCollection(connection);
		
		connection.close();
		
		String emailBody = "Backup Summary report for " + startDate + "\n";
		emailBody = emailBody +	"Good Backups : " + goodNum + "\n";
		emailBody = emailBody + "Bad Backups : " + badNum + "\n";
		emailBody = emailBody + "Total Backups : " + totalNum + "\n";
		emailBody = emailBody + "Percent Succeeded : " + perSucceeded + "\n";
		emailBody = emailBody + "Average backup per day : " + aveBackups + "\n";
		emailBody = emailBody + "\n" + "Garbage Collection status \n" + gc_details;
		
		
		Xml x = new Xml();
		String xmlString = x.sendEmail(toEmail, fromEmail, "Avamar Monthly Report", emailBody, "smtp.am.mt.mtnet");
		
		Rabbitmq rmq = new Rabbitmq();

		rmq.setHostname(rabbitServer);
		rmq.setLogin(RMQVirtualHost, RMQPassword, RMQUsername);

		Channel ch;
		
		ch = rmq.setupChannel();
		AMQP.BasicProperties properties = new AMQP.BasicProperties();
		properties.setDeliveryMode(2);
		boolean durable = true;
		ch.queueDeclare(RMQQueue, durable, false, false, null);
		ch.basicPublish("", RMQQueue, properties, xmlString.getBytes());
		l.programStop(log);
		ch.close();
		
		//new PushCo("BackupInfo","Avamar Monthly Backup stats have run for " + "avamar:report:" + yr + "." + mn ,true);
		jd.close();
		System.exit(0);
	}


	private static void monthReport(Connection connection) throws Exception {


		String monthReport = "select  status_code, count(status_code) as backup_count , sum(num_of_files) as num_of_files_day,sum(bytes_scanned)/1024/1024/1024/1024 as bytes_scanned_month, sum(bytes_scanned)/1024/1024/1024/1024 as bytes_scanned_day ,sum(bytes_modified_sent)/1024/1024/1024 as bytes_modified_sent_day " +
				"from v_activities_2 " + 
				"where (recorded_date between '" + startDate + "' and '" + endDate + "') "  +
				//"where (recorded_date between '" + startDate + "' and '" + endDate + "') and domain not in ('/MTC/Desktops','/MTC/Test') and client_name not like 'us99s%' " +
				"group by status_code " +
				"order by backup_count desc";
		PreparedStatement sql = connection.prepareStatement(monthReport);
		ResultSet resultSet = sql.executeQuery();
		String statusCode = "";
		while (resultSet.next()) {
			statusCode = resultSet.getString("status_code");
			if (statusCode.equals("30000")) goodNum = goodNum + Integer.parseInt(resultSet.getString("backup_count"));
			else if (statusCode.equals("30005")) goodNum = goodNum + Integer.parseInt(resultSet.getString("backup_count"));
			else if (statusCode.equals("30999")) badNum = badNum + Integer.parseInt(resultSet.getString("backup_count"));
			else if (statusCode.equals("30998")) badNum = badNum + Integer.parseInt(resultSet.getString("backup_count"));
			else if (statusCode.equals("30901")) badNum = badNum + Integer.parseInt(resultSet.getString("backup_count"));
			else if (statusCode.equals("30900")) badNum = badNum + Integer.parseInt(resultSet.getString("backup_count"));
			else if (statusCode.equals("30910")) badNum = badNum + Integer.parseInt(resultSet.getString("backup_count"));
			//else System.out.println(statusCode + " " + resultSet.getString("backup_count") + "-" + lookupEvent(connection,statusCode) +  "  This has not been included in calc");
		}
		totalNum = badNum + goodNum;
		perSucceeded = 100 - (float) badNum / goodNum;
		
		long daysInMonth = Misc.calculateDays(startDate.replace("-", "/"), endDate.replace("-", "/"));
		
		aveBackups = (int) (totalNum / daysInMonth);

	}

	private static String GarbageCollection(Connection connection) throws Exception {
		
		String GCSQL = "select start_time, end_time, bytes_recovered, passes from v_gcstatus " + 
		"where start_time > '" + startDate + "'" +
		"order by start_time asc";
		
		PreparedStatement sql = connection.prepareStatement(GCSQL);
		ResultSet resultSet = sql.executeQuery();
		String returnString = "";
		while (resultSet.next()) {
			returnString = returnString + resultSet.getString("start_time") + "\t" + resultSet.getString("end_time") + "\t" + resultSet.getString("bytes_recovered") + "\t" + resultSet.getString("passes") + "\n";
		}
		return returnString;
	}

	

	

}
	



